import React, { useState, useEffect } from 'react';
import { View, Picker, Form, Input, Text, Textarea } from '@tarojs/components';
import { Date, Heart } from '@nutui/icons-react-taro';
import { Button, Toast, Overlay, Loading } from '@nutui/nutui-react-taro';
import Taro, { useLoad } from '@tarojs/taro';
import dayjs from 'dayjs';
import { taskApi } from '../../../services/taskApi';
import './index.scss';

const TaskCreate = () => {
  // 任务时长选择器
  // const durationOptions = ['7天', '14天', '21天', '30天'];
  // const [selectedDuration, setSelectedDuration] = useState('7天');
  // const onDurationChange = e => {
  //   setSelectedDuration(durationOptions[e.detail.value])
  // }

  const today = dayjs().format('YYYY-MM-DD');
  const sevenDaysLater = dayjs().add(7, 'day').format('YYYY-MM-DD');

  const [startDate, setStartDate] = useState(today);
  const [endDate, setEndDate] = useState(sevenDaysLater);
  const [selectedAssignee, setSelectedAssignee] = useState('');
  const [assigneeOptions, setAssigneeOptions] = useState([]);
  const [selectedAssigneeIndex, setSelectedAssigneeIndex] = useState(0);
  const [assigneeList, setAssigneeList] = useState([]);
  const [selectedAssigneeId, setSelectedAssigneeId] = useState('');
  const [loading, setLoading] = useState(false);
  const [loadingAssignees, setLoadingAssignees] = useState(true);
  const [taskDesc, setTaskDesc] = useState('');
  const [showToast, setShowToast] = useState(false);
  const [toastMsg, setToastMsg] = useState('');
  const [toastType, setToastType] = useState('fail');

  useEffect(() => {
    setLoadingAssignees(true);
    taskApi.getAssigneeList().then(res => {
      if (res && res.length > 0) {
        setAssigneeList(res);
        const assignees = res.map(item => item.name);
        setAssigneeOptions(assignees);
        setSelectedAssignee(assignees[0]);
        setSelectedAssigneeId(res[0].id);
      }
    }).finally(() => {
      setLoadingAssignees(false);
    });
  }, []);

  // 使用useLoad钩子在页面加载时预加载
  useLoad(() => {
    // 使用Taro.nextTick确保在UI渲染后执行
    Taro.nextTick(() => {
      if (selectedAssigneeId) {
        // 获取当前路由实例并使用preload
        const router = Taro.getCurrentInstance().router;
        if (router && router.preload) {
          router.preload({
            url: `/package-manage/pages/ai-assist/index?assigneeId=${selectedAssigneeId}`
          });
        }
      }
    });
  });

  // 使用dayjs格式化日期
  const formatDate = (dateStr) => {
    return dayjs(dateStr).format('ddd MMM D YYYY');
  };

  // 显示Toast提示
  const showToastMessage = (message, type = 'fail') => {
    setToastMsg(message);
    setToastType(type);
    setShowToast(true);
    setTimeout(() => {
      setShowToast(false);
    }, 2000);
  };

  const onSubmit = e => {
    const formData = e.detail.value;
    
    // 表单验证
    if (!formData.taskName || formData.taskName.trim() === '') {
      showToastMessage('请输入任务标题');
      return;
    }

    if (!formData.taskDesc || formData.taskDesc.trim() === '') {
      showToastMessage('请输入任务描述');
      return;
    }

    if (!selectedAssigneeId) {
      showToastMessage('请选择任务负责人');
      return;
    }

    // 验证开始日期不能大于结束日期
    if (dayjs(startDate).isAfter(dayjs(endDate))) {
      showToastMessage('开始日期不能晚于结束日期');
      return;
    }
    
    const params = {
      assignee_id: selectedAssigneeId,
      start_time: `${formatDate(startDate)} 00:00:00 GMT+0800`,
      end_time: `${formatDate(endDate)} 00:00:00 GMT+0800`,
      basic_task: formData.taskName,
      detail_task: formData.taskDesc,
    }

    setLoading(true);
    taskApi.createTask(params).then(res => {
      console.log(res.task_id);

      showToastMessage('任务创建成功', 'success');

      // 发送一个事件通知任务列表页面更新数据
      Taro.eventCenter.trigger('taskCreated', { taskId: res.task_id });

      // 延迟执行跳转，确保 Toast 显示完成
      setTimeout(() => {
        Taro.navigateBack();
      }, 1500);
    }).catch(error => {
      showToastMessage('创建失败，请重试');
    }).finally(() => {
      setLoading(false);
    });
  }

  const onStartDatePickerChange = e => {
    setStartDate(e.detail.value)
  }

  const onEndDatePickerChange = e => {
    setEndDate(e.detail.value)
  }

  const onAssigneeChange = e => {
    const index = e.detail.value;
    setSelectedAssigneeIndex(index);
    setSelectedAssignee(assigneeOptions[index]);
    setSelectedAssigneeId(assigneeList[index].id);
  }

  const handleAIAssist = () => {
    Taro.navigateTo({
      url: `/package-manage/pages/ai-assist/index?assigneeId=${selectedAssigneeId}`
    });
  };

  useEffect(() => {
    const taskContent = Taro.getStorageSync('taskContent');
    if (taskContent) {
      // 设置到状态中
      setTaskDesc(taskContent);
      // 使用完后清除存储
      Taro.removeStorageSync('taskContent');
    }
  }, []);

  return (
    <View className='task-create'>
      <Form onSubmit={onSubmit}>
        <View className="task-create__form-item">
          <Text className="task-create__label">任务标题</Text>
          <View className="task-create__input-wrapper">
            <Input name='taskName' type="text" className="task-create__input" placeholder="输入任务标题..." />
          </View>
        </View>

        <View className="task-create__form-item">
          <Picker name='assignee' mode='selector' range={assigneeOptions} onChange={onAssigneeChange} value={selectedAssigneeIndex}>
            <View className='task-create__selector-label'>
              <Text>分配给：</Text>
              <Text style={{ color: '#3b82f6', fontSize: '16px' }}>{selectedAssignee}</Text>
            </View>
          </Picker>
        </View>

        {/* <View className="task-create__form-item">
          <Text className="task-create__label">时间安排</Text>
          <Picker name='duration' mode='selector' range={durationOptions} onChange={onDurationChange} value={selectedDuration}>
            <View className='task-create__selector-label'>
              <Text>为期：</Text>
              <Text>{selectedDuration}</Text>
            </View>
          </Picker>
        </View> */}

        <View className="task-create__date-picker-item">
          <View className="task-create__date-picker-start">
            <Picker name='startDate' mode='date' onChange={onStartDatePickerChange} value={startDate}>
              <View className="task-create__form-item">
                <Text className="task-create__label">开始日期</Text>
                <View className="task-create__data-picker-wrapper">
                  <Text>{startDate}</Text>
                  <Date color='#6b7280' />
                </View>
              </View>
            </Picker>
          </View>
          <View className="task-create__date-picker-end">
            <Picker name='endDate' mode='date' onChange={onEndDatePickerChange} value={endDate}>
              <View className="task-create__form-item">
                <Text className="task-create__label">结束日期</Text>
                <View className="task-create__data-picker-wrapper">
                  <Text>{endDate}</Text>
                  <Date color='#6b7280' />
                </View>
              </View>
            </Picker>
          </View>
        </View>

        <View className="task-create__form-item">
          <View className="task-create__selector-label" style={{ marginBottom: '10px' }}>
            <Text>任务描述</Text>
            <Button size='mini' type="primary" icon={<Heart className='nut-icon-am-breathe nut-icon-am-infinite' />} onClick={handleAIAssist}>
              AI辅助
            </Button>
          </View>
          <View className="task-create__textarea-wrapper">
            <Textarea
              name='taskDesc'
              className="task-create__textarea"
              placeholder="输入任务描述..."
              value={taskDesc}
              onInput={e => setTaskDesc(e.detail.value)}
            />
          </View>
        </View>

        <Button formType='submit' size='large' block type='primary' loading={loading} disabled={loading}>保存并发布</Button>
      </Form>

      {/* 内嵌Toast组件 */}
      <Toast
        visible={showToast}
        type={toastType}
        msg={toastMsg}
        onClose={() => setShowToast(false)}
      />

      {/* 全屏遮罩加载中 */}
      <Overlay visible={loading} zIndex={1000}>
        <View style={{
          display: 'flex',
          flexDirection: 'column',
          alignItems: 'center',
          justifyContent: 'center',
          height: '100%'
        }}>
          <Loading type="spinner" color="#fff" />
          <Text style={{ color: '#fff', marginTop: '10px' }}>提交中...</Text>
        </View>
      </Overlay>
    </View>
  );
};

export default TaskCreate;
